package com.ling.ling_push.pusher;

import android.hardware.Camera.CameraInfo;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.widget.Toast;

import com.ling.ling_push.MainActivity;
import com.ling.ling_push.params.AudioParam;
import com.ling.ling_push.params.VideoParam;
import com.example.my_push.jni.PushNative;

public class LivePusher implements Callback {
	private String TAG=this.getClass().getSimpleName();
	private SurfaceHolder surfaceHolder;
	private VideoPusher videoPusher;
	private AudioPusher audioPusher;
	private PushNative pushNative;
	private VideoParam videoParam;
	private AudioParam audioParam;
	public LivePusher(SurfaceHolder surfaceHolder) {
		this.surfaceHolder = surfaceHolder;
		surfaceHolder.addCallback(this);
		prepare();
	}

	/**
	 * 预览准备
	 */
	private void prepare() {
		pushNative = new PushNative();
		//实例化视频推流器
		videoParam = new VideoParam(1280, 720, CameraInfo.CAMERA_FACING_BACK);
		videoPusher = new VideoPusher(surfaceHolder,videoParam,pushNative);
		//实例化音频推流器
		audioParam = new AudioParam();
		audioPusher = new AudioPusher(audioParam,pushNative);
		pushNative.setOnConnectListener(new PushNative.ConnectListener() {
			@Override
			public void connectError(int errorCode, String errorMsg) {
				Log.e(TAG,errorMsg);
				onUi(errorMsg);
			}

			@Override
			public void connectSuccess() {
				Log.e(TAG,"connectSuccess");
				videoPusher.startPush();
				audioPusher.startPush();
			}
		});
	}
	private void onUi(final String errorMsg){
		MainActivity.GetActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(MainActivity.GetActivity().getApplicationContext(),errorMsg,Toast.LENGTH_LONG).show();

			}
		});
	}
	/**
	 * 切换摄像头
	 */
	public void switchCamera() {
		videoPusher.switchCamera();
	}

	/**
	 * 开始推流
	 */
	public void startPush(String url) {
		//初始化X264以及rtmp
		pushNative.native_init();
		pushNative.setVideoEncInfo(videoPusher.getVideoParam().getWidth(),videoPusher.getVideoParam().getHeight(),videoParam.getFps(),videoParam.getBitrate());
		pushNative.setAudioEncInfo(audioParam.getSampleRateInHz(),audioParam.getChannel());
		pushNative.startPush(url);
	}
	
	
	/**
	 * 停止推流
	 */
	public void stopPush() {
		videoPusher.stopPush();
		audioPusher.stopPush();
		pushNative.stopPush();
		pushNative.release();
	}
	public void AudioPause(){
		audioPusher.AudioPause();
	}
	/**
	 * 释放资源
	 */
	public void release() {
		videoPusher.stopPush();
		audioPusher.stopPush();
		pushNative.stopPush();
	 	videoPusher.release();
		audioPusher.release();
		pushNative.release();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
	//	stopPush();
	//	release();
	}
	
}
